package com.xyh.transaction.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {
    private User user;
    private Collection<Role> roles; // 修改为角色集合
    private Collection<Permission> permissions; // 权限集合

    public LoginUser(User user, Collection<Role> roles,Collection<Permission> permissions) {
        this.user = user;
        this.roles = roles;
        this.permissions = permissions;
    }

    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null) {
            return authorities;
        }
        // 通常情况下，角色的字符串表示会以 "ROLE_" 前缀开头，而权限的字符串表示则不包含该前缀。
        // 这种约定是由Spring Security规定的，并且也是默认情况下的行为。

        // 添加角色字符
        authorities = roles.stream()
                .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getRoleStr())) // 角色以"ROLE_"为前缀
                .collect(Collectors.toList());
        // 添加权限字符
        authorities.addAll(permissions.stream()
                .map(permission ->  new SimpleGrantedAuthority(permission.getPermissionName()))
                .collect(Collectors.toSet()));
        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return user.getStatus() != 0;
    }
}
